<?php
// +----------------------------------------------------------------------------
// | TkeAdmin [三十年河东三十年河西,莫欺少年穷.!]
// +----------------------------------------------------------------------------
// | Copyright (c) 2014 http://www.itdaodan.com All rights reserved.
// +----------------------------------------------------------------------------
// | Author: PHP@妖孽 <dino_ma@163.com>
// +----------------------------------------------------------------------------
/**
 * @todo  curl
 */
class Curl{
	
	/**
	 * @todo curl post请求方式
	 */
	function curl_post($url, array $post = NULL, array $options = array()){ 
		$post = http_build_query($post) ;
	    $defaults = array( 
	        CURLOPT_POST => 1, 
	        CURLOPT_HEADER => 0, 
	        CURLOPT_URL => $url, 
	        CURLOPT_FRESH_CONNECT => 1, 
	        CURLOPT_RETURNTRANSFER => 1, 
	        CURLOPT_FORBID_REUSE => 1, 
	        CURLOPT_TIMEOUT => 4, 
	        CURLOPT_POSTFIELDS => $post 
	    ); 
	
	    $ch = curl_init(); 
	    curl_setopt_array($ch, ($options + $defaults)); 
	    
	    if( ! $result = curl_exec($ch)){
	    	//错误处理
	    	$curl_errno = curl_errno($ch);
	   		$curl_error_msg = curl_error($ch);
	   		\Think\Log::write("CURL--POST接口调用异常,url:{$url}.'--'.{$curl_errno}:{$curl_error_msg}".http_build_query($post).PHP_EOL);
	    }
	    \Think\Log::write("CURL--POST接口调用成功,url:{$url}.'--'.Post:{$post}".PHP_EOL);
	    curl_close($ch); 
	    return $result; 
	} 
	
	/**
	 * @todo curl get
	 * @param string $url
	 * @param array $param
	 * @throws \Exception
	 * @return mixed
	 */
	function get($url, $param=array()){
		if(!is_array($param)){
			throw new \Exception("参数必须为array");
		}
		$p='';
		foreach($param as $key => $value){
			$p=$p.$key.'='.$value.'&';
		}
		if(preg_match('/\?[\d\D]+/',$url)){//matched ?c
			$p='&'.$p;
		}else if(preg_match('/\?$/',$url)){//matched ?$
			$p=$p;
		}else{
			$p='?'.$p;
		}
		$p=preg_replace('/&$/','',$p);
		$url=$url.$p;
		//echo $url;
		$httph =curl_init($url);
		curl_setopt($httph, CURLOPT_SSL_VERIFYPEER, 0);
		curl_setopt($httph, CURLOPT_SSL_VERIFYHOST, 1);
		curl_setopt($httph,CURLOPT_RETURNTRANSFER,1);
		curl_setopt($httph, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
		 
		curl_setopt($httph, CURLOPT_RETURNTRANSFER,1);
		curl_setopt($httph, CURLOPT_HEADER,1);
		$rst=curl_exec($httph);
		curl_close($httph);
		return $rst;
	}
	
}